package com.yz.hanlp;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.common.Term;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chn
 * @version 1.0
 */
@Service
public class HanlpServiceImpl implements HanlpService {


    /**
     * 以文本读取html文件
     * @param fileName
     * @return
     */
    public static String readFileContent(String fileName) {
        try {
            File file = new File(fileName);
            BufferedReader reader = null;
            StringBuffer sbf = new StringBuffer();
            try {
                InputStreamReader fReader = new InputStreamReader(new FileInputStream(file),"UTF-8");
                reader = new BufferedReader(fReader);
                String tempStr;
                while ((tempStr = reader.readLine()) != null) {
                    sbf.append(tempStr);
                }
                reader.close();
                return sbf.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
            return sbf.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 转码
     * @param str
     * @param newCharset
     * @return
     */
    public static String changeCharset(String str, String newCharset){
        try {
            if (str != null) {
                //用默认字符编码解码字符串。
                byte[] bs = str.getBytes();
                //用新的字符编码生成字符串
                return new String(bs, newCharset);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 完善html 排版 回显效果
     * @param htmlStr
     * @return
     */
    public static String perfectHtml(String htmlStr){
        try {
            //删除 微软用户" name="author">
            htmlStr = htmlStr.replace("<meta content=\"微软用户\" name=\"author\">","");
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            //删除超链接问题
            htmlStr = htmlStr.replace("href=","");
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            //修改首行下划线样式问题
            int p2 = htmlStr.indexOf("class=\"p2\"");
            htmlStr = htmlStr.substring(0,p2) +"style=\"border-bottom: 1px solid red;\""+ htmlStr.substring(p2+10,htmlStr.length());
        }catch (Exception e){
            e.printStackTrace();
        }

        //修改首行时间空格问题
        String regex = "\\d{4}年\\d{1,2}月\\d{1,2}日";
        Pattern p = Pattern.compile(regex);
        Matcher matcher = p.matcher(htmlStr);
        if (matcher.find()) {
            String time = matcher.group(0);
            int timeIndex = htmlStr.indexOf(time);
            htmlStr = htmlStr.substring(0,timeIndex) +"</span><span style=\"float: right;\">"+time+"</span>"+ htmlStr.substring(timeIndex+time.length(),htmlStr.length());
        }
        return htmlStr;
    }


    /**
     * 增加html文本样式
     * @param htmlStr
     * @return
     */
    public static String addHtmlStyle(String htmlStr){
        try {
            String style = "</style>";
            int styleIndex = htmlStr.indexOf(style);
            String frontStr = htmlStr.substring(0,styleIndex);
            String afterStr = htmlStr.substring(styleIndex,htmlStr.length());
            htmlStr = frontStr + ".s7{color:blue;text-decoration:underline;}" +afterStr;
            return htmlStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return htmlStr;
    }

    public static String replacePersonName(String htmlStr){
        try {
            List<String> nameList = getValueList(htmlStr, "nr");
            HashSet set = new HashSet();
            if (nameList.size()>0){
                for(int i=0;i<nameList.size();i++){
                    String name = nameList.get(i);
                    //姓名去重
                    if(set.add(name)){
                        //过滤长度为1的名字
                        if(name.length()>=2){
                            htmlStr = htmlStr.replace(name,"<span title=\"人员\" class=\"s7\">"+name+"</span>");
                        }
                    }
                }
            }
            return htmlStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static String replaceOrganizeName(String htmlStr){
        try {
            List<String> nameList = getOrganizeNameList(htmlStr);
            HashSet set = new HashSet();
            if (nameList.size()>0){
                for(int i=0;i<nameList.size();i++){
                    String name = nameList.get(i);
                    //组织名去重
                    if(set.add(name)){
                        //过滤长度为1的组织名
                        if(name.length()>=2){
                            htmlStr = htmlStr.replace(name,"<span title=\"组织\" class=\"s7\">"+name+"</span>");
                        }
                    }
                }
            }
            return htmlStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }







    /**
     * 整理人员身份信息
     * @param htmlStr
     * @return
     */
    public static String replacePersonInfo(String htmlStr){
        try {
            List<String> idCardList = getIdCard(htmlStr);
            HashSet set = new HashSet();
            if (idCardList.size()>0){
                for(int i=0;i<idCardList.size();i++){
                    String idCard = idCardList.get(i);
                    //身份证号去重
                    if(set.add(idCard)){
                        htmlStr = htmlStr.replace(idCard,"<span title=\"身份证号\" class=\"s7\">"+idCard+"</span>");
                    }
                }
            }
            List<String> phoneList = getPhoneNum(htmlStr);
            set = new HashSet();
            if (phoneList.size()>0){
                for(int i=0;i<phoneList.size();i++){
                    String phoneNum = phoneList.get(i);
                    //手机号去重
                    if(set.add(phoneNum)){
                        htmlStr = htmlStr.replace(phoneNum,"<span title=\"手机号\" class=\"s7\">"+phoneNum+"</span>");
                    }
                }
            }
            return htmlStr;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }




    /**
     * 从分词当中提取出人名
     *
     * @param line
     * @param tag
     * @return
     */
    public static List<String> getValueList(String line, String tag) {
        List<String> valueList = new ArrayList<String>();
        try{
            if (line == null || line.length() < 1) {
                return valueList;
            }
            Segment segment = HanLP.newSegment().enableNameRecognize(true).enableOrganizationRecognize(true);
            List<Term> termList = segment.seg(line);
            for (int i = 0; i < termList.size(); i++) {
                String word = termList.get(i).word;
                String nature = termList.get(i).nature.toString();
                if (nature == tag) {
                    valueList.add(word);
                }
            }
            return valueList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return valueList;
    }


    public static List<String> getOrganizeNameList(String line) {
        List<String> valueList = new ArrayList<String>();
        try {
            String[] natureList = {"nt", "ntc", "ntcb", "ntcf", "ntch", "nth", "nto", "nts", "ntu", "ni", "nic", "nis", "nit"};
            Segment segment = HanLP.newSegment().enableNameRecognize(true).enableOrganizationRecognize(true);
            List<Term> termList = segment.seg(line);
            for (int i = 0; i < termList.size(); i++) {
                String word = termList.get(i).word;
                String nature = termList.get(i).nature.toString();
                if (Arrays.asList(natureList).contains(nature)) {
                    valueList.add(word);
                }
            }
            LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(valueList);
            valueList.clear();
            valueList.addAll(linkedHashSet);
            return valueList;
        }catch (Exception e){
            e.printStackTrace();
        }
        if (line == null || line.length() < 1) {
            return valueList;
        }
        return valueList;
    }

    /**
     * 提取身份证号码
     *
     * @return
     */
    public static List<String> getIdCard(String splitStrings) {
        List<String> idCardList = new ArrayList<>();
        try {
            String idCardregex = "\\d{15}(\\d{2}[0-9xX])?";
            Pattern p = Pattern.compile(idCardregex);
            Matcher m = p.matcher(splitStrings);
            while (m.find()) {
                idCardList.add(m.group());
            }
            return idCardList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return idCardList;
    }

    /**
     * 提取电话号码
     *
     * @return
     */
    public static List<String> getPhoneNum(String splitStrings) {
        List<String> phoneNumList = new ArrayList<>();
        try {
            String phoneRegex = "0?(13|14|15|18|17)[0-9]{9}";
            Pattern p = Pattern.compile(phoneRegex);
            Matcher m = p.matcher(splitStrings);
            while (m.find()) {
                phoneNumList.add(m.group());
            }
            return phoneNumList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return phoneNumList;
    }


}
